/*
 * @Description:
 * @Autor: lcz
 * @Date: 2022-09-08 16:00:54
 * @LastEditors: lcz
 * @LastEditTime: 2022-11-15 18:23:17
 */
import { Table, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import React, { useState, useMemo, useRef, useEffect } from 'react';
import useSearch from '../../hooks/useSearch';
import { uuid } from '@webchuanzhou96/lcz-utils';
import zhCN from 'antd/es/locale/zh_CN';
import CheckboxSelect from '../../components/selfComponent/checkboxSelect/CheckboxSelect.tsx';

import { useSize } from 'ahooks';
import './index.less';
import useResizeTableCol from '../../hooks/useResizeTableCol';
import ResizeableTitle from '../../components/selfComponent/resizeableTable/ResizeableTitle';
interface DataType {
  key: React.ReactNode;
  name: string;
  age: number;
  address: string;
  children?: DataType[];
}

const data: DataType[] = [
  {
    key: 1,
    name: 'John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.John Brown sr.',
    age: 60,
    address: 'New York No. 1 Lake Park',
    children: [
      {
        key: 11,
        name: 'John Brown',
        age: 42,
        address: 'New York No. 2 Lake Park',
      },
      {
        key: 12,
        name: 'John Brown jr.',
        age: 30,
        address: 'New York No. 3 Lake Park',
        children: [
          {
            key: 121,
            name: 'Jimmy Brown',
            age: 16,
            address: 'New York No. 3 Lake Park',
          },
        ],
      },
      {
        key: 13,
        name: 'Jim Green sr.',
        age: 72,
        address: 'London No. 1 Lake Park',
        children: [
          {
            key: 131,
            name: 'Jim Green',
            age: 42,
            address: 'London No. 2 Lake Park',
            children: [
              {
                key: 1311,
                name: 'Jim Green jr.',
                age: 25,
                address: 'London No. 3 Lake Park',
              },
              {
                key: 1312,
                name: 'Jimmy Green sr.',
                age: 18,
                address: 'London No. 4 Lake Park',
              },
            ],
          },
        ],
      },
    ],
  },
  {
    key: 2,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 3,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 4,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 5,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 6,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 7,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 8,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 9,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 10,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 11,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 12,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: 13,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
];

const testList = [
  { label: 'Name', value: 'name' },
  { label: 'Age', value: 'age' },
  { label: 'Address', value: 'address' },
];

const TableCmp = () => {
  const { getColumnSearchProps } = useSearch();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [cloumnSelectShow, setCloumnSelectShow] = useState<string[]>(testList ? testList.map(i => i.value) : []);

  const tableRef = useRef(null);
  const tableWrapperSize = useSize(tableRef);
  const [wrapperWidth, setWrapperWidth] = useState<number>();

  const columns: any = useMemo(() => {
    let columnsArr = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        wordKey: 'name',
        // width: 600,
        render: (
          text:
            | string
            | number
            | boolean
            | React.ReactElement<any, string | React.JSXElementConstructor<any>>
            | React.ReactFragment
            | React.ReactPortal
            | null
            | undefined
        ) => {
          return {
            children: <span>{text}</span>,
          };
        },
        ...getColumnSearchProps('name'),
        // filterIcon: (filtered: boolean) => <EyeOutlined />,
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        wordKey: 'age',
        // width: 800,
        render: (
          text:
            | string
            | number
            | boolean
            | React.ReactElement<any, string | React.JSXElementConstructor<any>>
            | React.ReactFragment
            | React.ReactPortal
            | null
            | undefined
        ) => {
          return {
            children: <span>{text}</span>,
          };
        },
        ...getColumnSearchProps('age'),
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
        wordKey: 'address',
        render: (
          text:
            | string
            | number
            | boolean
            | React.ReactElement<any, string | React.JSXElementConstructor<any>>
            | React.ReactFragment
            | React.ReactPortal
            | null
            | undefined
        ) => {
          return {
            children: <span className={`${text}`}>{text}</span>,
          };
        },
        defaultSortOrder: 'descend',
        sorter: (a: any, b: any) => a.address.length - b.address.length,
        ...getColumnSearchProps('address'),
      },
      {
        title: '测试',
        dataIndex: 'address',
        key: 'address',
        wordKey: 'address',
        width: '300',
        render: (
          text:
            | string
            | number
            | boolean
            | React.ReactElement<any, string | React.JSXElementConstructor<any>>
            | React.ReactFragment
            | React.ReactPortal
            | null
            | undefined
        ) => {
          return {
            children: <span className={`${text}`}>{text}</span>,
          };
        },
        defaultSortOrder: 'descend',
        sorter: (a: any, b: any) => a.address.length - b.address.length,
        ...getColumnSearchProps('address'),
      },
    ].filter(i => {
      if (cloumnSelectShow.includes(i.wordKey)) {
        return i;
      }
    });
    if (columnsArr.length > 0) {
      let copyTitle = JSON.parse(JSON.stringify(columnsArr[columnsArr.length - 1].title));
      columnsArr[columnsArr.length - 1].title = (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>{copyTitle}</div>
          <CheckboxSelect
            optionsList={testList}
            optionsListSelected={cloumnSelectShow}
            changeCallback={(data: any) => {
              setCloumnSelectShow(data);
              // (function () {
              //   setTableColumns(columns);
              // })();
              console.log('callback data---->', data);
            }}
          />
          {/* <EyeOutlined style={{ cursor: 'pointer' }} /> */}
        </div>
      );
    }
    console.log(columnsArr, 'columnsArr,2233');
    return columnsArr;
  }, [cloumnSelectShow]);

  const { colIsInit, tableColumns } = useResizeTableCol(wrapperWidth, tableRef, columns);

  const rowSelection: TableRowSelection<DataType> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };
  //   JSON.parse(JSON.stringify(Array(100).fill(data[1]))).map((i,index)=>{
  //     i.key = index;
  //     return i
  // })
  const dataSource = [
    ...data,
    ...JSON.parse(JSON.stringify(Array(100).fill(data[1]))).map((i: { key: string }, index: string) => {
      i.key = uuid() + index;
      return i;
    }),
  ];
  console.log(dataSource, 223);
  const pageSizeOptionsArr = [10, 20, 50, 100];
  const pagination = useMemo(() => {
    return {
      total: dataSource.length,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total: number) => `总共 ${total} 条`,
      onChange: (page: number, pageSize: number) => {
        console.log(page, pageSize, 2233);
        setPage(page);
        setPageSize(pageSize);
      },
      pageSize: pageSize,
      pageSizeOptions: pageSizeOptionsArr.includes(pageSize) ? pageSizeOptionsArr : [pageSize, ...pageSizeOptionsArr],
      defaultCurrent: 1,
      current: page,
    };
  }, [page, pageSize]);

  //获取外层dom元素的宽度
  useEffect(() => {
    if (tableWrapperSize) {
      setWrapperWidth(tableWrapperSize.width);
    }
  }, [tableRef, tableWrapperSize]);

  return (
    <div>
      <ConfigProvider locale={zhCN}>
        <div ref={tableRef}>
          {colIsInit ? (
            <Table
              size='small'
              scroll={{ x: 1300 }}
              // columns={columns}tableColumns
              columns={tableColumns}
              dataSource={dataSource}
              loading={false}
              pagination={pagination}
              components={{
                header: {
                  cell: ResizeableTitle,
                },
              }}
              onRow={record => {
                return {
                  onClick: event => {
                    console.log(event, record, '单机');
                  }, // 点击行
                  onDoubleClick: event => {},
                  onContextMenu: event => {},
                  onMouseEnter: event => {}, // 鼠标移入行
                  onMouseLeave: event => {},
                };
              }}
              // rowSelection={true ? rowSelection : undefined}
              // bordered={true}
              // title={() => 'Header'}
              // footer={() => 'Footer'}
            />
          ) : null}
        </div>
      </ConfigProvider>
    </div>
  );
};
export default TableCmp;
